package me.seu.demo.serializable;

import com.alibaba.fastjson.JSON;

import java.io.*;

/**
 * FastJsonTest
 *
 *
 * @number 53669
 * @since 2021/3/29 下午3:47
 */
public class FastJsonTest {

    public static void main(String[] args) {
        Student student = new Student();
        student.setAge(18);
        student.setName("张五");

        //将javabean转成json
        String str = JSON.toJSONString(student);
        System.out.println("fastJson:" + str);

        //将json转成java bean
        Student myUser = JSON.parseObject(str, Student.class);
        System.out.println("fastJson 反序列化：" + myUser.getName() + "-" + myUser.getAge() + "岁");

        System.out.println("---------------");
        String s = readFile();
        System.out.println("jdk string: " + s);

        Student myUser2 = JSON.parseObject(s, Student.class);
        System.out.println("fastJson 反序列化：" + myUser2.getName() + "-" + myUser2.getAge() + "岁");

    }

    /**
     * 读出文件
     */
    private static String readFile() {
        File file02 = new File("studentStream.txt");
        FileInputStream is = null;
        StringBuilder stringBuilder = null;
        try {
            if (file02.length() != 0) {
                /**
                 * 文件有内容才去读文件
                 */
                is = new FileInputStream(file02);
                InputStreamReader streamReader = new InputStreamReader(is);
                BufferedReader reader = new BufferedReader(streamReader);
                String line;
                stringBuilder = new StringBuilder();
                while ((line = reader.readLine()) != null) {
                    // stringBuilder.append(line);
                    stringBuilder.append(line);
                }
                reader.close();
                is.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return String.valueOf(stringBuilder);
    }

}
